<?php

namespace App\Models\System;

use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Laravel\Lumen\Auth\Authorizable;

class User extends Model implements AuthenticatableContract, AuthorizableContract
{
    use Authenticatable, Authorizable, HasFactory, SoftDeletes;

    protected $table = 'sys_users';
    //设置时间格式
    protected $dateFormat = 'Y-m-d H:i:s';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'role_ids' => 'array',
        'tags' => 'array',
        'geographic' => 'array',
        'geographic_name' => 'array',
    ];
    /**
     * Prepare a date for array / JSON serialization.
     *
     * @param  \DateTimeInterface  $date
     * @return string
     */
    protected function serializeDate(\DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }
    /**
     * 获取用户角色列表
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function roles()
    {
        return $this->belongsToMany('App\Models\System\Role','sys_role_users','user_id','role_id')->withTimestamps();
    }

    /**
     * 判断用户是否具有某个角色
     * @param $role
     * @return bool
     */
    public function hasRole($role)
    {
        if (is_string($role)){
            return $this->roles->contains('name', $role);
        }
        //判断拥有该权限的角色和当前用户的角色是否有重合存在交集。双感叹号相当于强制转换为布尔类型
        $waitCheckRoleList = $role ? Arr::pluck($role, 'name') : [];
        $currentUserRoleList = $this->roles ? $this->roles->pluck('name')->toArray() : [];
        return !! array_intersect($waitCheckRoleList, $currentUserRoleList);
    }

    /**
     * 判断用户是否具有某权限
     * @param $permission
     * @return bool
     */
    public function hasPermission($permission)
    {
        if ($permission['is_public'] == 1){//公共权限直接返回true
            return true;
        }else{
            //判断是否是超级管理员
            if ($this->hasRole('super-admin')){
                return true;
            }else{
                return $this->hasRole($permission['roles'] ?? []);
            }
        }
    }
    /**
     * 轻巧版判断是否具有权限
     * @param $permName
     * @return bool
     */
    public function hasPermissionByPermName($permName)
    {
        $permission = (new \App\Services\System\Permission())->getCacheSimplePermDataByName($permName);
        //dump($permission);
        if ($permission){
            return $this->hasPermission($permission);
        }
        return false;
    }
    /**
     * 获取当前用户拥有的权限列表，
     * @param false $isRefresh
     * @return array|mixed
     */
    public function getPermissionList($isRefresh = false)
    {
        $cacheKey = 'syspermission:permlist_user:'.$this->getKey();
        $cacheData = Cache::get($cacheKey);
        if (!$cacheData || $isRefresh) {
            $cacheData = [];
            //获取所有权限列表
            $allSysPermissionList = (new \App\Services\System\Permission())->getCacheSimplePermList();
            if (!empty($allSysPermissionList)){
                foreach ($allSysPermissionList as $permId => $permName){
                    $permission = (new \App\Services\System\Permission())->getCacheSimplePermDataById($permId);
                    if ($permission && $this->hasPermission($permission)){
                        $cacheData[] = $permName;
                    }
                }
            }
            Cache::put($cacheKey, $cacheData, Carbon::now()->addSeconds(60));
        }
        return $cacheData;
    }
}
